import React, { memo, Fragment, useState, useRef } from "react";
import { withRouter } from "react-router-dom";
import { Button, Switch, message, Modal } from "antd";

import { custom } from "services/common";
import HYFromSearch from "components/formSearch";
import HYTableComponent from "components/tableData";
/*这个组件针对性 强很多 需要根据接口返回值要做具体调节 其实也可以外面拿到数据 然后里面就根据数据渲染，传几个回调函数出去，用来分页,删除等*/
import HYModalCom from "./modal";

const HYUserList = memo(function (props: any) {
  const formItem = [
    { type: "Input", name: "truename", label: "真实姓名" },
    {
      type: "Select",
      name: "status",
      label: "禁用",
      options: "status",
      style: { width: 180 },
    },
  ];
  const tableConfig = {
    //表头数据
    thead: [
      { title: "用户id", dataIndex: "id", key: "id" },
      { title: "用户名", dataIndex: "username", key: "username" },
      { title: "真实姓名", dataIndex: "truename", key: "truename" },
      { title: "手机号", dataIndex: "phone", key: "phone" },
      {
        title: "权限",
        dataIndex: "role_str",
        key: "role_str",
        render: (value: any, item: any) => <div>{value}</div>,
      },
      {
        title: "禁启用",
        dataIndex: "status",
        key: "status",
        render: (value: any, item: any) => (
          <Switch
            checkedChildren="开启"
            unCheckedChildren="关闭"
            defaultChecked={value === "1" ? true : false}
            onChange={() => changeSwitch(item)}
          />
        ),
      },
      {
        title: "操作",
        dataIndex: "operation",
        key: "operation",
        width: 215,
        render: (value: any, item: any) => (
          <div className="btn">
            <Button type="primary" onClick={() => edit(item)}>
              编辑
            </Button>
            <Button onClick={() => deleteItem(item)}>删除</Button>
          </div>
        ),
      },
    ],
    border: false, //是否显示边框
    // isShowCheckbox:true, //显示多选框
    isShowBatch: true, //是否显示批量删除
    // 表数据--根据请求获取
    requestData: {
      //url 可以还传一个method
      url: "/user/list/",
      method: "post",
      data: {
        pageNumber: 1,
        pageSize: 10,
        name: "",
      },
    },
    rowKey: "id",
  };
  const isAddBtn = {
    leftRow: 20,
    rightRow: 4,
  };
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [ids, setIds] = useState<string>();
  const [configLoad, setConfigLoad] = useState(false);
  const [switchFlag, setSwitchFlag] = useState(false);
  // Ref
  const tableRef = useRef(null);
  const currentRef: any = tableRef.current;
  const modalRef: any = useRef(null);
  //  切换状态
  const changeSwitch = async (val: any) => {
    const { id, status } = val;
    try {
      if (switchFlag) return;
      setSwitchFlag(true);
      const res: any = await custom({
        url: "/user/status/",
        data: { id: id, status },
      });
      message.success(res.message);
      setSwitchFlag(false);
    } catch (error) {
      setSwitchFlag(false);
      message.warn(error);
    }
  };
  // 删除单个
  const deleteItem = (value: any) => {
    setIsModalVisible(true);
    setIds(value.id);
  };
  // 编辑
  const edit = (objVal: any) => {
    modalRef.current.isEdit(objVal);
  };
  const onFinish = (val: any, form: any) => {
    const { pageNumber, pageSize } = tableConfig.requestData.data;
    const requestData = {
      pageNumber,
      pageSize,
      truename: val && val.truename ? val.truename : '',
      status: val && val.status ? val.status : '',
    };
    currentRef.init(requestData);
  };
  // 批量删除
  const batch = (id: string) => {
    setIsModalVisible(true);
    setIds(id);
  };
  const handleOk = async () => {
    setConfigLoad(true);
    const res: any = await custom({ url: "/user/delete/", data: { id: ids } });
    message.success(res.message);
    const { pageNumber, pageSize, name } = tableConfig.requestData.data;
    currentRef.init({ pageNumber, pageSize, name });
    setConfigLoad(false);
    setIsModalVisible(false);
  };
  const addUser = () => {
    (modalRef.current as any).isShowModal()
  };
  return (
    <Fragment>
      {/* 这是封装后的组件 */}
      <HYFromSearch formItem={formItem} submit={onFinish} isAddBtn={isAddBtn}>
        <Button type="primary" style={{ width: "120px" }} onClick={addUser}>
          新增用户
        </Button>
      </HYFromSearch>
      <div style={{ height: "30px" }}></div>
      {/* 表格 */}
      <HYTableComponent
        tableConfig={tableConfig}
        batch={batch}
        ref={tableRef}
      />
      {/* 模态框 */}
      <Modal
        title="提示"
        visible={isModalVisible}
        onOk={handleOk}
        onCancel={() => setIsModalVisible(false)}
        okText="确认"
        cancelText="取消"
        confirmLoading={configLoad}
      >
        <p>
          删除后不可恢复是否{" "}
          <span style={{ color: "red", fontSize: "20px" }}>删除？</span>
        </p>
      </Modal>
      {/* 用户增加弹窗  requestData用于添加修改后重新发送请求刷新数据*/}
      <HYModalCom ref={modalRef} requestData={onFinish} ></HYModalCom>
    </Fragment>
  );
});

export default withRouter(HYUserList);
